package client;

import java.io.*;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;

/**
 * Settings stored in a singleton
 */
public  class Settings {

	private static Settings instance;
	public static synchronized Settings getInstance(){
		if (instance == null)
			instance = load();
		return instance;
		
	}

	private String host = "127.0.0.1";

	public void setHost(String h){
		host = h;
	}

	public String getHost() {
		return host;
	}

	private int port = 80;

	public void setPort(int p){
		port = p;
	}

	public int getPort() {
		return port;
	}

	private static Settings load(){
		XStream xs = new XStream(new StaxDriver());
		Reader r = null;
		try {
			r = new BufferedReader(new FileReader("config.xml"));
		} catch (FileNotFoundException e) {
			System.out.println("Default config is loaded!");
		}
		
		if (r != null) {
			return (Settings)xs.fromXML(r);
		}
		Settings defaultSet = new Settings();
		defaultSet.setHost("127.0.0.1");
		defaultSet.setPort(80);
		defaultSet.save();
		return defaultSet;
	}

	public void save(){
		XStream xs = new XStream(new StaxDriver());
		try {
			Writer w = new PrintWriter(new BufferedWriter(new FileWriter("config.xml")));
			xs.toXML(this, w);
			w.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}



}
